#include <stdio.h>
#include <stdlib.h>

typedef struct LNode{
    int data;
    struct LNode *next;
}LNode, *LinkList;

int ListInitiate(LinkList *L)
{
    *L = (LinkList)malloc(sizeof(LNode));
    if (*L == NULL) { return 0; }
    (*L)->next = NULL;
    return 1;
}

int ListLength(LinkList L)
{
    int len = 0;
    LNode *p = L->next;
    while (p != NULL)
    {
        len++;
        p = p->next;
    }
    return len;
}

int ListInsert(LinkList L, int i, int e)
{
    if (i < 1 || i > ListLength(L) + 1) { return 0; }
    LNode *p = L;
    int j = 0;
    while (p != NULL && j < i - 1) { p = p->next; j++; }
    if (p == NULL) { return 0; }
    LNode *s = (LNode*)malloc(sizeof(LNode));
    s->data = e;
    s->next = p->next;
    p->next = s;
    return 1;
}

int ListDelete(LinkList L, int i, int *e)
{
    if (i < 1 || i > ListLength(L)) { return 0; }
    LNode *p = L;
    int j = 0;
    while (p != NULL && j < i - 1) { p = p->next; j++; }
    if (p == NULL) { return 0; }
    LNode *q = p->next;
    *e = q->data;
    p->next = q->next;
    free(q);
    return 1;
}

int ListGet(LinkList L, int i, int *e)
{
    if (i < 1 || i > ListLength(L)) { return 0; }
    LNode *p = L;
    int j = 0;
    while (p != NULL && j < i) { p = p->next; j++; }
    if (p == NULL) { return 0; }
    *e = p->data;
    return 1;
}

int Destroy(LinkList *L)
{
    LNode *p = *L, *q;
    while (p != NULL)
    {
        q = p->next;
        free(p);
        p = q;
    }
    *L = NULL;
    return 1;
}

int main(void)
{
    LinkList L;
    int i, x;
    if (!ListInitiate(&L))
    {
        printf("初始化失败！\n");
        return 1;
    }
    for (i = 0; i < 10; i++)
    {
        if (!ListInsert(L, i + 1, i + 1))
        {
            printf("插入数据元素失败！\n");
            return 1;
        }
    }
    if (!ListDelete(L, 4, &x))
    {
        printf("删除数据元素失败！\n");
        return 1;
    }
    printf("删除的元素值为：%d\n", x);
    for (i = 1; i <= ListLength(L); i++)
    {
        if (!ListGet(L, i, &x))
        {
            printf("获取数据元素失败！\n");
            return 1;
        }
        printf("%d ", x);
    }
    printf("\n");
    if (!Destroy(&L))
    {
        printf("销毁线性表失败！\n");
        return 1;
    }
    return 0;
}